//
//  PostViewController.m
//  HeSiad
//
//  Created by ZC on 15/4/25.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "PostViewController.h"
#import "AppDelegate.h"
#import "ViewController.h"
#define postURL @"http://192.168.1.110:8888/hesaid/index.php/Hesaid/post"
@interface PostViewController (){
    AppDelegate *app;
    CLLocationManager *locationManager;
    CLGeocoder *geocoder;
    CLPlacemark *Placemark;
    NSString *string;
    NSString *str1;
    UIAlertView *_alert;
    NSString *currentTime;
}

@end

@implementation PostViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"发帖子";
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    [self getTime];
    [self positioning];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 定位
-(void)positioning{
    //创建定位管理器
    locationManager = [[CLLocationManager alloc] init];
    geocoder=[[CLGeocoder alloc]init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        //设置定位权限 仅ios8有意义
        [locationManager requestWhenInUseAuthorization];// 前台定位
        
        //  [locationManager requestAlwaysAuthorization];// 前后台同时定位
    }
    //开始定位
    [locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"error:%@",error);
    if (error.code==kCLErrorLocationUnknown) {
        NSLog(@"无法获取到当前位置信息");
    }else if (error.code==kCLErrorNetwork){
        NSLog(@"网络异常");
    }else if (error.code==kCLErrorDenied){
        NSLog(@"您的phone禁用获取位置服务");
    }
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取位置信息失败"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLLocation *currentLocation=newLocation;
    _longitude = currentLocation.coordinate.longitude;
    _latitude = currentLocation.coordinate.latitude;
    NSLog(@"%@",currentLocation);
    if (currentLocation!=nil) {
        //停止获取地址位置
        [locationManager stopUpdatingLocation];
        //转换地址
        [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
            //            NSLog(@"找地标：%@，error：%@",placemarks,error);
            if (error==nil&&[placemarks count]>0) {
                Placemark=[placemarks lastObject];
                NSString *s1=[[NSString alloc]init];
                //地标的名字
                s1=[NSString stringWithFormat:@"%@",Placemark.name];
                NSLog(@"%@",s1);
            }else{
                UIAlertView *Alert = [[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [Alert show];
                
            }
        }];
    }
}

#pragma mark - 自动获取当时时间

-(void)getTime{
    NSDateFormatter *fomatter=[[NSDateFormatter alloc]init];
    [fomatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *nowTime=[fomatter stringFromDate:[NSDate date]];
    currentTime=nowTime;
}


- (IBAction)published:(id)sender {
    //获取当下发帖的时间
    [self getTime];
    NSString *jd = [NSString stringWithFormat:@"%f",_longitude];
    NSString *wd = [NSString stringWithFormat:@"%f",_latitude];
    NSURL *url=[NSURL URLWithString:postURL];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    str1 =[NSString stringWithFormat:@"message_content=%@&message_time=%@&user_id=%@&message_longitude=%@&message_latitude=%@&message_showtime=%@",self.content.text,currentTime,app.user_id,jd,wd,self.ShowTime.text];
    NSData *data=[str1 dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:string waitUntilDone:YES];
        int intstr = [string intValue];
        if (intstr == 1) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"发表成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            _alert=alert;
            [alert show];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"发表失败" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
    }];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"viewVC"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)refreshData{
    
}
@end
